package data

import (
	"backend/internal/biz"
	"backend/internal/models"
	"backend/internal/service"
	"context"

	"go.uber.org/zap"
)

type userRepo struct {
	data *Data
	log  *zap.Logger
}

func NewUserRepo(data *Data, log *zap.Logger) service.UserRepo {
	return &userRepo{
		data: data,
		log:  log,
	}
}
func (r *userRepo) GetUserByID(id uint64) (*biz.User, error) {
	var user models.User
	if err := r.data.db.Where("id = ?", id).First(&user).Error; err != nil {
		r.log.Error("GetUserByID error", zap.Error(err))
		return nil, err
	}
	return user.ToBiz(), nil
}
func (r *userRepo) GetUserByUserName(ctx context.Context, usrName string) (*biz.User, error) {
	var user models.User
	if err := r.data.db.Where("user_name = ?", usrName).First(&user).Error; err != nil {
		r.log.Error("GetUserBy error", zap.Error(err))
		return nil, err
	}
	return user.ToBiz(), nil
}
func (r *userRepo) Create(ctx context.Context, usr *biz.User) (*biz.User, error) {
	var user models.User
	user = models.User{
		UserName: usr.UserName,
		Password: user.Password,
	}
	err := r.data.DB(ctx).Create(&user).Error
	if err != nil {
		r.log.Error("CreateUser error", zap.Error(err))
		return nil, err
	}
	return user.ToBiz(), nil
}

func (r *userRepo) FindByID(ctx context.Context, id uint64) (*biz.User, error) {
	var user models.User
	if err := r.data.db.First(&user, id).Error; err != nil {
		return nil, err
	}
	return user.ToBiz(), nil
}
